<template>
  <view class="page-container">
    <!-- 页面标题和操作按钮 -->
    <view class="page-header">
      <view class="page-title">商户管理</view>
      <button type="primary" @click="openAddTenantDialog">添加商户</button>
    </view>
    
    <!-- 搜索和筛选 - 替换搜索栏 -->
    <view class="filter-box">
      <!-- 替换为普通输入框 -->
      <view class="search-box">
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索商户名称/联系人" 
          class="search-input"
          @confirm="searchTenants"
        />
        <button class="search-btn" @click="searchTenants">搜索</button>
      </view>
      <uni-data-select v-model="statusFilter" :localdata="statusOptions" @change="filterByStatus" />
    </view>
    
    <!-- 商户列表 -->
    <uni-table ref="table" :loading="loading" border stripe emptyText="暂无商户数据">
      <uni-tr>
        <uni-th align="center">商户名称</uni-th>
        <uni-th align="center">联系人</uni-th>
        <uni-th align="center">联系电话</uni-th>
        <uni-th align="center">小程序状态</uni-th>
        <uni-th align="center">商户状态</uni-th>
        <uni-th align="center">创建时间</uni-th>
        <uni-th align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="(item, index) in tenantList" :key="index">
        <uni-td align="center">{{ item.tenant_name }}</uni-td>
        <uni-td align="center">{{ item.contact_name }}</uni-td>
        <uni-td align="center">{{ item.contact_phone }}</uni-td>
        <uni-td align="center">
          <uni-tag :text="item.miniapp_status ? '已开通' : '未开通'" :type="item.miniapp_status ? 'success' : 'warning'" />
        </uni-td>
        <uni-td align="center">
          <uni-tag :text="item.status === 1 ? '正常' : '禁用'" :type="item.status === 1 ? 'success' : 'error'" />
        </uni-td>
        <uni-td align="center">{{ formatDate(item.created_at) }}</uni-td>
        <uni-td align="center">
          <view class="action-buttons">
            <button size="mini" @click="editTenant(item)">编辑</button>
            <button size="mini" type="primary" @click="manageMiniapp(item)">小程序设置</button>
            <button size="mini" :type="item.status === 1 ? 'warn' : 'primary'" @click="toggleTenantStatus(item)">
              {{ item.status === 1 ? '禁用' : '启用' }}
            </button>
          </view>
        </uni-td>
      </uni-tr>
    </uni-table>
    
    <!-- 分页 -->
    <uni-pagination :total="total" :pageSize="pageSize" :current="currentPage" @change="handlePageChange" />
    
    <!-- 添加/编辑商户弹窗 -->
    <uni-popup ref="tenantFormPopup" type="dialog">
      <uni-popup-dialog title="商户信息" :before-close="true" @close="handleDialogClose" @confirm="submitTenantForm">
        <view class="tenant-form">
          <uni-forms ref="tenantForm" :modelValue="tenantForm" :rules="tenantRules">
            <uni-forms-item name="tenant_name" label="商户名称">
              <uni-easyinput v-model="tenantForm.tenant_name" placeholder="请输入商户名称" />
            </uni-forms-item>
            <uni-forms-item name="contact_name" label="联系人">
              <uni-easyinput v-model="tenantForm.contact_name" placeholder="请输入联系人姓名" />
            </uni-forms-item>
            <uni-forms-item name="contact_phone" label="联系电话">
              <uni-easyinput v-model="tenantForm.contact_phone" placeholder="请输入联系电话" />
            </uni-forms-item>
            <uni-forms-item name="contact_email" label="电子邮箱">
              <uni-easyinput v-model="tenantForm.contact_email" placeholder="请输入电子邮箱" />
            </uni-forms-item>
            <uni-forms-item name="address" label="地址">
              <uni-easyinput v-model="tenantForm.address" placeholder="请输入地址" />
            </uni-forms-item>
            <uni-forms-item name="description" label="商户描述">
              <uni-easyinput type="textarea" v-model="tenantForm.description" placeholder="请输入商户描述" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </uni-popup-dialog>
    </uni-popup>
    
    <!-- 小程序设置弹窗 -->
    <uni-popup ref="miniappFormPopup" type="dialog">
      <uni-popup-dialog title="小程序设置" :before-close="true" @close="handleDialogClose" @confirm="submitMiniappForm">
        <view class="miniapp-form">
          <uni-forms ref="miniappForm" :modelValue="miniappForm" :rules="miniappRules">
            <uni-forms-item name="appid" label="AppID">
              <uni-easyinput v-model="miniappForm.appid" placeholder="请输入微信小程序AppID" />
            </uni-forms-item>
            <uni-forms-item name="app_secret" label="AppSecret">
              <uni-easyinput v-model="miniappForm.app_secret" placeholder="请输入微信小程序AppSecret" />
            </uni-forms-item>
            <uni-forms-item name="app_name" label="小程序名称">
              <uni-easyinput v-model="miniappForm.app_name" placeholder="请输入小程序名称" />
            </uni-forms-item>
            <uni-forms-item name="theme_color" label="主题颜色">
              <uni-easyinput v-model="miniappForm.theme_color" placeholder="请输入主题颜色(如#FF6B00)" />
            </uni-forms-item>
            <uni-forms-item name="payment_enabled" label="支付功能">
              <switch :checked="miniappForm.config.payment_enabled" @change="(e) => miniappForm.config.payment_enabled = e.detail.value" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      tenantList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      searchKeyword: '',
      statusFilter: '',
      statusOptions: [
        { value: '', text: '全部状态' },
        { value: '1', text: '正常' },
        { value: '0', text: '禁用' }
      ],
      tenantForm: {
        tenant_name: '',
        contact_name: '',
        contact_phone: '',
        contact_email: '',
        address: '',
        description: '',
      },
      tenantRules: {
        tenant_name: {
          rules: [{ required: true, errorMessage: '请输入商户名称' }]
        },
        contact_name: {
          rules: [{ required: true, errorMessage: '请输入联系人姓名' }]
        },
        contact_phone: {
          rules: [{ required: true, errorMessage: '请输入联系电话' }]
        }
      },
      currentTenantId: '',
      miniappForm: {
        appid: '',
        app_secret: '',
        app_name: '',
        theme_color: '#FF6B00',
        config: {
          payment_enabled: false
        }
      },
      miniappRules: {
        appid: {
          rules: [{ required: true, errorMessage: '请输入微信小程序AppID' }]
        },
        app_secret: {
          rules: [{ required: true, errorMessage: '请输入微信小程序AppSecret' }]
        },
        app_name: {
          rules: [{ required: true, errorMessage: '请输入小程序名称' }]
        }
      }
    }
  },
  mounted() {
    this.loadTenantList();
  },
  methods: {
    // 加载商户列表
    async loadTenantList() {
      try {
        this.loading = true;
        
        const result = await uniCloud.callFunction({
          name: 'admin-tenant',
          data: {
            action: 'getTenants',
            params: {
              page: this.currentPage,
              pageSize: this.pageSize,
              keyword: this.searchKeyword,
              status: this.statusFilter
            }
          }
        });
        
        const data = result.result;
        if (data.code === 0) {
          this.tenantList = data.data;
          this.total = data.total;
        } else {
          uni.showToast({
            title: data.message || '获取商户列表失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error(e);
        uni.showToast({
          title: '获取商户列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索商户
    searchTenants() {
      this.currentPage = 1;
      this.loadTenantList();
    },
    
    // 筛选状态
    filterByStatus() {
      this.currentPage = 1;
      this.loadTenantList();
    },
    
    // 处理分页变化
    handlePageChange(e) {
      this.currentPage = e.current;
      this.loadTenantList();
    },
    
    // 打开添加商户弹窗
    openAddTenantDialog() {
      this.currentTenantId = '';
      this.tenantForm = {
        tenant_name: '',
        contact_name: '',
        contact_phone: '',
        contact_email: '',
        address: '',
        description: '',
      };
      this.$refs.tenantFormPopup.open();
    },
    
    // 编辑商户
    editTenant(tenant) {
      this.currentTenantId = tenant.tenant_id;
      this.tenantForm = {
        tenant_name: tenant.tenant_name,
        contact_name: tenant.contact_name,
        contact_phone: tenant.contact_phone,
        contact_email: tenant.contact_email || '',
        address: tenant.address || '',
        description: tenant.description || '',
      };
      this.$refs.tenantFormPopup.open();
    },
    
    // 小程序设置
    async manageMiniapp(tenant) {
      this.currentTenantId = tenant.tenant_id;
      this.loading = true;
      
      try {
        const res = await uniCloud.callFunction({
          name: 'admin-tenant',
          data: {
            action: 'getMiniappConfig',
            tenant_id: tenant.tenant_id
          }
        });
        
        if (res.result.code === 0) {
          const miniapp = res.result.data;
          if (miniapp) {
            this.miniappForm = {
              appid: miniapp.appid || '',
              app_secret: miniapp.app_secret || '',
              app_name: miniapp.app_name || '',
              theme_color: miniapp.theme_color || '#FF6B00',
              config: miniapp.config || { payment_enabled: false }
            };
          } else {
            this.miniappForm = {
              appid: '',
              app_secret: '',
              app_name: tenant.tenant_name + '点餐小程序',
              theme_color: '#FF6B00',
              config: { payment_enabled: false }
            };
          }
          this.$refs.miniappFormPopup.open();
        } else {
          uni.showToast({
            title: res.result.message || '获取小程序配置失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error(e);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 提交商户表单
    async submitTenantForm() {
      try {
        await this.$refs.tenantForm.validate();
        
        this.loading = true;
        
        const res = await uniCloud.callFunction({
          name: 'admin-tenant',
          data: {
            action: this.currentTenantId ? 'updateTenant' : 'addTenant',
            tenant_id: this.currentTenantId,
            tenant: this.tenantForm
          }
        });
        
        if (res.result.code === 0) {
          uni.showToast({
            title: this.currentTenantId ? '更新成功' : '添加成功',
            icon: 'success'
          });
          this.$refs.tenantFormPopup.close();
          this.loadTenantList();
        } else {
          uni.showToast({
            title: res.result.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error(e);
        uni.showToast({
          title: '表单验证失败，请检查输入',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 提交小程序设置表单
    async submitMiniappForm() {
      try {
        await this.$refs.miniappForm.validate();
        
        this.loading = true;
        
        const res = await uniCloud.callFunction({
          name: 'admin-tenant',
          data: {
            action: 'saveMiniappConfig',
            tenant_id: this.currentTenantId,
            miniapp: this.miniappForm
          }
        });
        
        if (res.result.code === 0) {
          uni.showToast({
            title: '小程序设置保存成功',
            icon: 'success'
          });
          this.$refs.miniappFormPopup.close();
          this.loadTenantList();
        } else {
          uni.showToast({
            title: res.result.message || '保存失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error(e);
        uni.showToast({
          title: '表单验证失败，请检查输入',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 切换商户状态
    async toggleTenantStatus(tenant) {
      try {
        const result = await uniCloud.callFunction({
          name: 'admin-tenant',
          data: {
            action: 'updateTenantStatus',
            tenant_id: tenant.tenant_id,
            status: tenant.status === 1 ? 0 : 1
          }
        });
        
        if (result.result.code === 0) {
          uni.showToast({
            title: '操作成功',
            icon: 'success'
          });
          this.loadTenantList();
        } else {
          uni.showToast({
            title: result.result.message || '操作失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error(e);
        uni.showToast({
          title: '操作失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 处理弹窗关闭
    handleDialogClose() {
      this.$refs.tenantFormPopup.close();
      this.$refs.miniappFormPopup.close();
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  }
}
</script>

<style>
.page-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.filter-box {
  display: flex;
  margin-bottom: 20px;
}

.filter-box .search-box {
  display: flex;
  flex: 1;
}

.filter-box .search-input {
  flex: 1;
  height: 36px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 0 10px;
}

.filter-box .search-btn {
  margin-left: 10px;
  height: 36px;
  line-height: 36px;
  font-size: 14px;
  padding: 0 15px;
}

.filter-box .uni-data-select {
  width: 150px;
  margin-left: 10px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 5px;
}

.tenant-form, .miniapp-form {
  padding: 10px;
}
</style> 